package com.bizmda.bizsip.sample.sink.longtcpnetty;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.bizmda.bizsip.common.BizUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * @Author: 史正烨
 * @Date: 2022/3/1 11:11 上午
 * @Description:
 */
@Service
@Slf4j
public class SampleServerService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void process(SampleMessage sampleMessage) {
        if (sampleMessage.getLength() == 0) {
            log.debug("收到心跳检测包!");
            return;
        }
        String str;
        log.debug("收到报文(长度:{}):\n{}",
                sampleMessage.getLength(), BizUtils.buildHexLog(sampleMessage.getData()));
        try {
            str = new String(sampleMessage.getData(),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            log.error("码制转换出错!",e);
            return;
        }
        JSONObject jsonObject = JSONUtil.parseObj(str);
        log.debug("jsonObject:\n{}",BizUtils.buildJsonLog(jsonObject));
        String replyTo = jsonObject.getStr("replyTo");
        String correlationId = jsonObject.getStr("correlationId");
        Message message = MessageBuilder.withBody(sampleMessage.getData())
                .setCorrelationId(correlationId).build();
        this.rabbitTemplate.send("", replyTo, message);
    }
}
